#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import json
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.forms import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from django.urls import reverse
from django.http import StreamingHttpResponse, FileResponse

from django.conf import settings
from django.core.files.storage import FileSystemStorage


from app01.forms.file import FolderModelForm, FileModelForm
from app01 import models
import requests


# http://127.0.0.1:8002/manage/1/file/
# http://127.0.0.1:8002/manage/1/file/?folder=1
def file(request, project_id):
    """ 文件列表 & 添加文件夹 """

    parent_object = None
    folder_id = request.GET.get('folder', "")
    if folder_id.isdecimal():
        parent_object = models.FileRepository.objects.filter(id=int(folder_id), file_type=2,
                                                             project=request.tracer.project).first()

    # GET 查看页面
    if request.method == "GET":

        breadcrumb_list = []
        parent = parent_object
        while parent:
            # breadcrumb_list.insert(0, {'id': parent.id, 'name': parent.name})
            breadcrumb_list.insert(0, model_to_dict(parent, ['id', 'name']))
            parent = parent.parent

        # 当前目录下所有的文件 & 文件夹获取到即可
        queryset = models.FileRepository.objects.filter(project=request.tracer.project)
        if parent_object:
            # 进入了某目录
            file_object_list = queryset.filter(parent=parent_object).order_by('-file_type')
        else:
            # 根目录
            file_object_list = queryset.filter(parent__isnull=True).order_by('-file_type')
        form = FolderModelForm(request, parent_object)

        context = {
            'form': form,
            "file_object_list": file_object_list,
            "breadcrumb_list": breadcrumb_list,
            'folder_object': parent_object
        }
        return render(request, 'file.html', context)

    # POST 添加文件夹 & 文件夹的修改
    fid = request.POST.get('fid', '')
    edit_object = None
    if fid.isdecimal():
        edit_object = models.FileRepository.objects.filter(id=int(fid), file_type=2, project=request.tracer.project).first()

    if edit_object:
        form = FolderModelForm(request, parent_object, data=request.POST, instance=edit_object)
    else:
        form = FolderModelForm(request, parent_object, data=request.POST)

    if form.is_valid():
        form.instance.project = request.tracer.project
        form.instance.file_type = 2
        form.instance.update_user = request.tracer.user
        form.instance.parent = parent_object
        form.save()
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


# http://127.0.0.1:8002/manage/1/file/delete/?fid=1
def file_delete(request, project_id):
    """ 删除文件 """
    fid = request.GET.get('fid')

    # 删除数据库中的 文件 & 文件夹 （级联删除）
    delete_object = models.FileRepository.objects.filter(id=fid, project=request.tracer.project).first()
    if delete_object.file_type == 1:  #1代表文件
        # 删除文件，将容量还给当前项目的已使用空间
        request.tracer.project.use_space -= delete_object.file_size
        request.tracer.project.save()

        # cos中删除文件
        # delete_file(request.tracer.project.bucket, request.tracer.project.region, delete_object.key)

        # 在数据库中删除当前文件
        delete_object.delete()

        return JsonResponse({'status': True})

   
    # 如果file_type为2，代表是文件夹，则需要删除文件夹下的所有文件
    total_size = 0
    key_list = []

    folder_list = [delete_object, ]
    for folder in folder_list:
        child_list = models.FileRepository.objects.filter(project=request.tracer.project, parent=folder).order_by('-file_type')
        for child in child_list:
            if child.file_type == 2:
                folder_list.append(child)
            else:
                # 文件大小汇总
                total_size += child.file_size

                # 删除文件
                key_list.append({"Key": child.key})

   

    # 删除数据库中的文件
    delete_object.delete()
    return JsonResponse({'status': True})


from utils import encrypt

@csrf_exempt
def file_post(request, project_id):
    """ 已上传成功的文件写入到数据 """
    if request.method == 'POST' and request.FILES['uploadFile']:
        upload_file = request.FILES['uploadFile']
        local_path = os.path.join(settings.MEDIA_ROOT ,settings.MEDIA_URL)
        print("local_path:",local_path)
        fs = FileSystemStorage(location=settings.MEDIA_ROOT)
        random_file_name = encrypt.magic_file_name(upload_file.name) # 66fcc5ebd7c5b66b7249098dd7923b51.PNG
        print("random_file_name:",random_file_name)
        filename = fs.save(random_file_name, upload_file)  

        uploaded_file_url = fs.url(random_file_name)  
        print("uploaded_file_url:",uploaded_file_url)
        parent_id=request.POST.get('parent_id')
        parent_object = None
        if parent_id and parent_id.isdecimal():
            parent_object = models.FileRepository.objects.filter(id=int(parent_id), project=request.tracer.project).first()


        # 将文件信息保存到数据库
        from app01.models import FileRepository
        file_repo = FileRepository(
            project=request.tracer.project,
            file_type=1,  # 假设 1 表示文件
            name=upload_file.name,
            file_size=upload_file.size,
            update_user=request.tracer.user,
            file_path=random_file_name,
            parent=parent_object

        )
        file_repo.save()

        request.tracer.project.use_space += upload_file.size
        request.tracer.project.save()





        result = {
            'id': file_repo.id,
            'name': file_repo.name,
            'file_size': file_repo.file_size,
            'username': file_repo.update_user.username,
            'datetime': file_repo.update_datetime.strftime("%Y年%m月%d日 %H:%M"),
            'download_url': request.build_absolute_uri(reverse('file_download', kwargs={"project_id": project_id, 'file_id': file_repo.id}))
        }
        print(result["download_url"])
        return JsonResponse({'status': True, 'data': result})

    return JsonResponse({'status': False, 'data': "文件错误"})


def file_download(request, project_id, file_id):
    """ 下载文件 """
    MNT_PATH ="D:" + settings.MEDIA_ROOT
    file_object = models.FileRepository.objects.filter(id=file_id, project_id=project_id).first()
    if not file_object:
        return JsonResponse({'status': False, 'data': "文件不存在"}, status=404)

    # res = requests.get(file_object.file_path)
    print(file_object.file_path.lstrip('/'))  #  media/5daf1411971614b2b8bbc39ca8265338.ini
    file_path = file_object.file_path
    file_path = os.path.join(MNT_PATH, file_path.lstrip('/'))
    print(file_path)
    if not os.path.exists(file_path):
        return JsonResponse({'status': False, 'data': "文件不存在"}, status=404)
    

    with open(file_path, 'rb') as f:
        response = HttpResponse(f.read(), content_type="application/octet-stream")
        from django.utils.encoding import escape_uri_path

        # 设置响应头：中文件文件名转义
        response['Content-Disposition'] = f"attachment; filename={escape_uri_path(file_object.name)};"
        return response